var $ = window.$;
var jade = require('jade');
var animate = require('../../util/animate');
var event = require('../../core/event');
var util = require('../../util/index');
var uiUtil = require('../../util/ui');
var config = require('../../core/config');


var _inited = false;
var _default = [
	'#990033','#cc3333','#ef6666','#ff9999',
	'#9933cc','#cc6699','#996699','#666699',
	'#003399','#0099cc','#99ccff','#ccccff',
	'#006633','#33cc33','#99cc00','#99cc66',
	'#ff9900','#ffff00','#ffea5d','#ffff66'
];

var ret = {
	init: function(){
		if(_inited){
			return;
		}
		event.bind(event.events.key.up, 'layer_edit', this);
		event.lock('key', 'layer_edit');

		_inited = true;
	},

	setManager: function (ma) {
		this.manager = ma;
	},

	onEvent: function(e, param){
		if(param.key == 27){
			this.hide();
			return event.result.stopAll;
		}
	},

	save: function () {
		var color = $('#layer_edit_color').val() || '';
		var name = $('#layer_edit_name').val() || '';
		if(color[0] != '#'){
			color = '#'+color;
		}
		if(!/#[a-f0-9]{6}/i.test(color)){
			color = _default[0];
		}
		this.manager._onDialogResult({
			color: color,
			name: name,
			idx: this.param ? this.param.idx : -1
		});
	},

	show: function(param){
		//参数准备, param外部已检验
		this.param = param;
		var tmpl = jade.compileFile('./tmpl/layer/dialog.jade');
		var html = tmpl({config: config});
		$('#dialog_layer').append(html);

		var self = this;
		this.parent = $('#dialog_layer_edit');

		var cells = this.parent.find('.select i');
		for(var i=0;i<cells.size();i++){
			cells.eq(i).css('backgroundColor', _default[i]);
		}
		if(param){
			$('#layer_edit_color').val(param.color);
			$('#layer_edit_name').val(param.name);
		}

		this.parent.on('click','.g_click', function(){
			var type = $(this).data('type');
			if(type == 'close'){
				self.save();
				self.hide();
			}
		});

		this.parent.on('click','i', function(e) {
			var idx = $(this).index();
			$('#layer_edit_color').val(_default[idx]);
		});

		this.parent.show();
		uiUtil.dialogInc();
		animate.slideInLeft(this.parent, 200);  //css值
		//event.trigger(event.events.global.blur);
	},

	hide: function(){
		var self = this;
		if(!this.parent){
			return;
		}
		animate.slideOutLeft(this.parent).then(function(){
			self.parent.remove();
			self.parent = null;
			uiUtil.dialogDec();
			event.unbind(event.events.key.up, 'layer_edit');
		});
		event.unlock();
		_inited = false;
	}
};

module.exports = ret;